function EEG = cvc_chef(bdffile,srate,filt,filt2,sphereflag)
% CVC_CHEF
%
%  Synopsis
%  ========
%
%  - survey mode -
%  EEG = cvc_chef(filename[.bdf])
%
%  - finalize mode -
%  EEG = cvc_chef(filename[.bdf],srate)
%  EEG = cvc_chef(filename[.bdf],srate,filt)
%  EEG = cvc_chef(filename[.bdf],srate,locut,hicut)
%  EEG = cvc_chef(filename[.bdf],srate,locut,hicut,sphereflag)
%
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     2009 - April 2013
%
%  Purpose
%  =======
%
%  Load and downsample BDF file on the fly. Incorporate E-prime
%  events from edat file. The output is saved as EEGLAB dataset.
%  Use survey mode to determine bad channels (in .ch file) and
%  rubbish time intervals (in .cut file). Finalize mode takes
%  all the files and does things in the right order.
%
%  Inputs
%  ======
%
%  Filename - Name of the Biosemi BDF file (with or without 
%  extension). This filename is also used for channel location
%  '.elp' or '.sfp' file,  bad channel file '.ch', and exported
%  e-prime edat file in Excel format with NO unicode file '.etx'.
%  Periods that are to be cut can be put in a cutfile with 
%  extension '.cut'.
%
%  srate - The desired output sampling rate. Note that decimation
%  is used, and the desired sampling rate must be an integer 
%  fraction of 2048Hz. If no sample rate is given (survey mode), 
%  then srate defaults to 64Hz and '_survey' will be added to the
%  output filename.
%
%  filt - Cell array with arguments to POP_EEGFILT. defaults to 
%  a 1-Hz high-pass filter, i.e. default filt={1, 0}. To disable 
%  filtering set it to {}.
%
%  locut - For two-stage filtering (recommended, as opposed to 
%  giving a cell array as filt), filter lo cut frequency in Hz.
%  Set to 0 to disable.
%
%  hicut - -"-, filter hi cut frequency in Hz. Set to 0 to disable.
%
%  sphereflag - Set to 1 to interpolate EEG channels spherically
%  instead of removing then. Non-EEG channels are unaffected by this.
%  The default value is 1 (ie. enabled). If set to 0, then the channels
%  will be removed instead.
%
%  Outputs
%  =======
%
%  EEG - EEGLAB dataset at the desired sampling rate, referenced 
%  to average EEG channel, with bad channels removed according to 
%  'filename.ch', rubbish intervals removed according to 
%  'filename.cut', channel locations according to either 
%  'filename.elp' or '.sfp' or '.ced'. If the elp/sfp/ced file 
%  is not found, then a standard location file is substituted.
%  E-Prime events are imported if the 'filename.etx' file is 
%  found (excel file WITHOUT unicode!).
%
%  Written File - Finalize mode, filename_%i_XXX.set is saved as
%  EEGLAB dataset, where %i is the output sampling rate. Survey
%  mode, '_survey' is added instead. XXX is a bunch of info about the 
%  options given to CVC_CHEF.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  %%%%%%%%%% HIDDEN FEATURE
%  skip - Set this to skip to the skip'th init sequence. 
%  should be 1 for normal operation.
skip = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin == 1
  chef_mode = 0; % survey mode
  srate = 128;
else
  chef_mode = 1;
end

if nargin<3 | chef_mode==0
  filt = 1; %{1, 0};
end
if nargin<4, filt2 = 0; end

if nargin<5, sphereflag = 1; end

%//////////
% open EEGLAB if not already opened
hh = findobj('tag', 'EEGLAB');
if isempty(hh)
  disp('cvc_chef: Starting EEGLAB.');
  eeglab
  hh = findobj('tag', 'EEGLAB');
  close(hh); % close it again ;) - 
  drawnow
end

[PATHSTR,NAME,EXT] = fileparts(bdffile);

% load bdf 

%%and chanlocs
%%, perhaps substitute standard locations

okchans=[];
for okext = {'.elp','.sfp','.ced'}
  chanlocsfile = fullfile(PATHSTR,[NAME okext{1}]);
  if exist(chanlocsfile,'file') 
    okchans = chanlocsfile;
    fprintf('Using %s as chanlocs.\n',chanlocsfile);
    break;
  end
end

%okchans = [];
if isempty(okchans)
  warning('elp file ignored, standard electrode locations loaded instead.');
  okchans = which('cvc_standard256.elp');
  edf = openbdf(fullfile(PATHSTR,[NAME '.bdf']));
  trigchan = edf.Head.NS;
  if trigchan<64
    okchans=strrep(okchans,'256','32');
  elseif trigchan<256
    okchans=strrep(okchans,'256','64');
  end
end
EEG.cvc.elpfile=okchans;
bdffile = fullfile(PATHSTR,[NAME '.bdf']);
EEG = cvc_load_bdf(bdffile,srate,okchans);

if 0
    EEG = iris_transform_events(EEG);
end

% import edat
edatfile =  fullfile(PATHSTR,[NAME '.etx']);
if exist(edatfile,'file')
  EEG = cvc_event_intelligent(EEG,edatfile,skip);
  EEG = cvc_event_convert2string(EEG);  
else
  warning('No etx-file found.');
end

% filter
if ~isempty(filt)
  EEG.data = double(EEG.data);
  if iscell(filt)
    EEG = pop_eegfilt( EEG, filt{:});
  else
    if filt>0
      EEG = pop_eegfilt( EEG, filt, 0); % lo cut
    end
    if filt2>0
      EEG = pop_eegfilt( EEG, 0, filt2); % hi cut
    end
    filt = {filt,filt2}; % used later for file-naming
  end
  EEG.data = single(EEG.data);
end

% cut time and remove bad channels and 
% re-reference
if chef_mode == 1
  % remove bad channels
  chfile =  fullfile(PATHSTR,[NAME '.ch']);
  if exist(chfile,'file')
    EEG = cvc_remove_channels(EEG,chfile,sphereflag);
  else
    warning('No ch-file found.');
  end
  
  % cut time
  cutfile =  fullfile(PATHSTR,[NAME '.cut']);
  if exist(cutfile,'file')
    EEG = cvc_timecut(EEG,cutfile);
  else
    warning('No cut-file found.');
  end
  
  % rereference, average remaining EEG electrodes
  refexch = [];
  for ch=1:length(EEG.chanlocs)
    if ~strcmp(EEG.chanlocs(ch).type,'EEG')
      refexch = [refexch, ch];
    end
  end
  EEG = pop_reref( EEG, [], 'exclude',refexch);

  % save EEGLAB set
  cstr='';
  for aa=1:length(filt)
    cstr = [cstr '_' strrep(num2str(filt{aa}),'.','x')];
  end
  if sphereflag
    sphstr = '_sph';
  else
    sphstr = '';
  end
  setfile = fullfile(PATHSTR,[NAME '_' strrep(num2str(EEG.srate),'.','x') cstr sphstr]);
  EEG = pop_saveset( EEG , 'filename',setfile,'savemode','onefile');
else
  % save EEGLAB set
  setfile = fullfile(PATHSTR,[NAME '_survey' num2str(srate)]);
  EEG = pop_saveset( EEG , 'filename',setfile,'savemode','onefile');
end
